package ua.com.minus1.lookbattle;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import ua.com.minus1.lookbattle.models.CacheFolder;
import ua.com.minus1.lookbattle.models.Pair;
import ua.com.minus1.lookbattle.net.HttpManager;
import ua.com.minus1.lookbattle.net.ImageManager;
import ua.com.minus1.lookbattle.net.URLManager;
import ua.com.minus1.lookbattle.utils.AppPreferences;
import ua.com.minus1.lookbattle.utils.BundleValues;

/**
 * Created with IntelliJ IDEA.
 * User: Denis
 * Date: 17.10.12
 * Time: 21:05
 * To change this template use File | Settings | File Templates.
 */
public class BattleFragment extends Fragment implements View.OnClickListener{
    private ViewGroup mContent;
    private ImageView mImageLeft;
    private ImageView mImageRight;
    private View mProgressLeft;
    private View mProgressRight;
    private HttpManager mHttpManager;
    private ImageManager mImageManager;
    private AppPreferences mPreferences;
    private int mCatId;
    Pair mLastResult;

    private Callbacks mCallbacks;
    private static final String SESSION_ID = "sessionId";
    private static final String LEFT_IMAGE = "leftImage";
    private static final String RIGHT_IMAGE = "rightImage";

    public interface Callbacks{
        void onClicksUpdate(int clicks);
    }

    public static BattleFragment newInstance(int catId) {
        Bundle args = new Bundle();
        args.putInt(BundleValues.CAT_ID, catId);

        BattleFragment f = new BattleFragment();
        f.setArguments(args);
        return f;
    }

    @Override
    public void onPause() {
        super.onPause();
        if(mImageManager != null)
        {
            mImageManager.stopLoading(mImageLeft);
            mImageManager.stopLoading(mImageRight);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mCatId = getArguments().getInt(BundleValues.CAT_ID);
        if(savedInstanceState != null && savedInstanceState.getString(SESSION_ID) != null)
        {
            mLastResult = new Pair();
            mLastResult.sessionId = savedInstanceState.getString(SESSION_ID);
            mLastResult.imageL = savedInstanceState.getString(LEFT_IMAGE);
            mLastResult.imageR = savedInstanceState.getString(RIGHT_IMAGE);
        }

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        mCallbacks = (Callbacks) activity;
        mHttpManager = new HttpManager(getActivity(), CacheFolder.HTTP_BATTLE);
        mImageManager = new ImageManager(getActivity(), CacheFolder.IMAGES_BATTLE);
        mPreferences = new AppPreferences(getActivity());
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if(mLastResult == null)
            startBattle();
        else
            loadImages(mLastResult.imageL, mLastResult.imageR);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContent = (ViewGroup) inflater.inflate(R.layout.fragment_battle, null);
        setupViews();
        return mContent;
    }

    private void setupViews() {
        View imageLeftLayout = mContent.findViewById(R.id.leftImage);
        View imageRightLayout = mContent.findViewById(R.id.rightImage);

        mImageLeft = (ImageView) imageLeftLayout.findViewById(R.id.image);
        mImageRight = (ImageView) imageRightLayout.findViewById(R.id.image);

        mProgressLeft = imageLeftLayout.findViewById(R.id.progress);
        mProgressRight = imageRightLayout.findViewById(R.id.progress);

        mImageLeft.setOnClickListener(this);
        mImageRight.setOnClickListener(this);
    }

    private void startBattle() {
        clearContent(true);
        String url = URLManager.getImagesURL(mPreferences.getUUID(), mCatId);
        mHttpManager.loadClass(url, Pair.class, new PairResultHandler());//, HttpManager.USE_CACHE);
    }

    public void onClick(View view) {
        clearContent(true);
        int id = view.getId() == R.id.leftImage ? URLManager.IMAGE_LEFT : URLManager.IMAGE_RIGHT;
        String url = URLManager.getImagesURL(mPreferences.getUUID(), mCatId, mLastResult.sessionId, id);
        mHttpManager.loadClass(url, Pair.class, new PairResultHandler());//, HttpManager.USE_CACHE);
        mLastResult = null;
    }

    private void clearContent(boolean clearCache) {
        if (clearCache) {
            mHttpManager.clearCache();
            mImageManager.clearCache();
        }
        mImageLeft.setImageBitmap(null);
        mImageRight.setImageBitmap(null);
        mProgressLeft.setVisibility(View.VISIBLE);
        mProgressRight.setVisibility(View.VISIBLE);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if(mLastResult != null)
        {
            outState.putString(SESSION_ID, mLastResult.sessionId);
            outState.putString(LEFT_IMAGE, mLastResult.imageL);
            outState.putString(RIGHT_IMAGE, mLastResult.imageR);
        }
    }

    private class PairResultHandler implements HttpManager.HttpResultHandler<Pair> {
        public void onResultLoadComplete(Pair result) {
            mLastResult = result;
            loadImages(mLastResult.imageL, mLastResult.imageR);
            mCallbacks.onClicksUpdate(mLastResult.cl);
        }
    }

    private void loadImages(String imageLURL, String imageRURL) {
        mImageManager.loadBitmap(imageLURL,  mImageLeft, new ImageManager.BitmapLoadListener() {
            public void onLoadComplete(Bitmap bitmap) {
                mProgressLeft.setVisibility(View.GONE);
            }
        }, ImageManager.USE_CACHE);
        mImageManager.loadBitmap(imageRURL,  mImageRight, new ImageManager.BitmapLoadListener() {
            public void onLoadComplete(Bitmap bitmap) {
                mProgressRight.setVisibility(View.GONE);
            }
        }, ImageManager.USE_CACHE);
    }

}
